package view;

import engine.Cell;
import model.Model;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.Cursor;

/**
 * Instantiation of {@link SimulationView} allowing for interaction.
 *
 * @author Ricardo Cruz {@literal <ricardo.pdm.cruz@gmail.com>}
 * @since  2014-11-13
 */
public class SimulationViewZoomin extends SimulationView
{
	private double mousex, mousey;

	public SimulationViewZoomin(SimulationViewListener listener) {
		super(0.25);
		setOnMousePressed(ev -> {
			setCursor(Cursor.MOVE);
		});
		setOnMouseReleased(ev -> {
			setCursor(null);
		});
		setOnMouseDragged(ev -> {
			xc -= (ev.getX()-mousex)/zoom;
			yc -= (ev.getY()-mousey)/zoom;
			setFocus(xc, yc);
			mousex = ev.getX();
			mousey = ev.getY();
			listener.moveSimulation(xc, yc);
		});
		setOnMouseExited(ev -> {
			repaint();
		});
		setOnMouseMoved(ev -> {
			mousex = ev.getX();
			mousey = ev.getY();
			repaint();
		});
		setOnScroll(ev -> {
			setZoom(zoom + Math.signum(ev.getDeltaY())/4.);
			listener.zoomSimulation(zoom);
		});
	}

	public void setFocus(double xc, double yc) {
		double w2 = (getWidth()/2)/zoom;
		double h2 = (getHeight()/2)/zoom;
		this.xc = Math.min(Model.getPetriWidth()-w2,Math.max(w2,xc));
		this.yc = Math.min(Model.getPetriHeight()-h2,Math.max(h2,yc));
	}

	public void setZoom(double zoom) {
		zoom = Math.min(14/4., Math.max(1/4., zoom));
		if(this.zoom != zoom) {  // keep center centered
			double centerx = isHover() ? (mousex-getWidth()/2) : 0;
			double centery = isHover() ? (mousey-getHeight()/2) : 0;
			xc += centerx/this.zoom - centerx/zoom;
			yc += centery/this.zoom - centery/zoom;
			this.zoom = zoom;
			setFocus(xc, yc);
		}
	}

	protected void drawCell(GraphicsContext gc, Cell cell, double x, double y, double size) {
		// draws some information next to cell, when the mouse is near it
		super.drawCell(gc, cell, x, y, size);
		if(isHover() && zoom*4 >= 6)
			// FIXME: try to get rid of x0 and cell.getX() here
			if(Math.abs(cell.getX()-x0()-mousex/zoom) <= 10*4 && Math.abs(cell.getY()-y0()-mousey/zoom) <= 10*4) {
				gc.setFill(Color.WHITE);
				gc.setLineWidth(0.1);
				gc.setFont(Font.font(size*1.2));
				gc.fillText(cell.getCurrentState().getName(), x+4, y-4);
			}
	}
}
